﻿using Aliphant.Common;
using Aliphant.Common.Managers;
using Aliphant.Mvvm.XEvent.Ioc;
using Aliphant.UI;
using Aliphant.UI.Windows;

using Microsoft.Win32;

using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Windows;

namespace Aliphant.Windows
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : UIWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;

            UIContainerLocator.Container.RegisterRegion(this.main, "main");
            UIContainerLocator.Container.RegisterRegion(this.siderbar, "siderbar");
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            UIContainerLocator.Container.NavigateTo("siderbar", "navigation");
            UIContainerLocator.Container.NavigateTo("main", "homePage");
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            bool isExit = true;

            if (ConfigManager.Instance.ExitApplication)
            {
                isExit = true;
            }
            else if (!ConfigManager.Instance.Settings.ExitNotify)
            {
                isExit = false;
            }
            else
            {
                var res = MessageBox.Show("确认退出？", "XDeskTool", MessageBoxButton.YesNo);
                if (res == MessageBoxResult.No)
                {
                    isExit = false;
                }
            }

            if (!isExit)
            {
                ConfigManager.Instance.ExitApplication = false;
                e.Cancel = true;
                this.Hide();
                return;
            }

            ClosePage("chatRobot");
            ClosePage("widgets");
            ClosePage("widgetCenter");

            base.OnClosing(e);
        }

        private void ClosePage(string name)
        {
            try
            {
                var obj = UIContainerLocator.Container.Resolve(name);
                if (obj is IPage page)
                {
                    page.Close();
                }
            }
            catch (InvalidOperationException iex)
            {
                Logger.Error(iex);
            }
        }
    }
}
